//Given an integer array nums and an integer k, return the k most frequent eleme
//nts. You may return the answer in any order. 
//
// 
// Example 1: 
// Input: nums = [1,1,1,2,2,3], k = 2
//Output: [1,2]
// Example 2: 
// Input: nums = [1], k = 1
//Output: [1]
// 
// 
// Constraints: 
//
// 
// 1 <= nums.length <= 105 
// k is in the range [1, the number of unique elements in the array]. 
// It is guaranteed that the answer is unique. 
// 
//
// 
// Follow up: Your algorithm's time complexity must be better than O(n log n), w
//here n is the array's size. 
// Related Topics 堆 哈希表 
// 👍 742 👎 0


package leetcode.editor.cn;

import java.util.*;

//Java：Top K Frequent Elements
class P347TopKFrequentElements {
    public static void main(String[] args) {
        Solution solution = new P347TopKFrequentElements().new Solution();
        // TO TEST
        solution.topKFrequent(new int[]{1, 2, 2, 3, 3, 1}, 2);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int[] topKFrequent(int[] nums, int k) {
            if (nums == null || nums.length == 0) {
                return null;
            }
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int num : nums) {
                map.put(num, 1 + map.getOrDefault(num, 0));
            }
            PriorityQueue<Map.Entry<Integer, Integer>> set = new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {
                @Override
                public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                    return -(o1.getValue() - o2.getValue());
                }
            });
            set.addAll(map.entrySet());
            int[] result = new int[k];
            int index = 0;
            while (index < k && !set.isEmpty()) {
                result[index++] = set.poll().getKey();
            }
            return result;

        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}